import axios from 'axios';
import n9 from './n9';
import Util from './util';
import store from '../stores/store';

const ajax = {
    baseUrl : $Config.baseUrl || '/admin/',
    loginUrl : $Config.loginUrl || '/login/',
    loginTimeout : $Config.loginTimeout || function() {
        alert('登录过期function未配置');
    },
    ajax(method, url, params, successCallback, failCallback, config) {
        var p, d;
        if (params) {
            for (var key in params) {
                var value = params[key];
                if (typeof value === 'object') {
                    params[key] = JSON.stringify(value);
                }
            }
        } else {
            params = {};
        }
        if (!$Config.MOCK) {
            params._ = new Date().getTime();
        }

        if (method == 'post' || method == 'put' || method == 'patch') {
            d = params;
        } else {
            p = params;
        }
        var conf = {
            method: method,
            url: url,
            params: p,
            data: d,
            transformRequest: [function (data) {
                let ret = '';
                for (let it in data) {
                    ret += '&' + encodeURIComponent(it) + '=' + encodeURIComponent(data[it]);
                }
                ret = ret.ltrim("&");
                return ret
            }]
        }
        if (config) {
            for (var key in config) {
                conf[key] = config[key];
            }
        }

        var request = http.request(conf).then(function (res) {
            // alert(JSON.stringify(res))
            //登录过期
            if (res.data.code == 211) {
                // alert("登录过期");
                n9.error('登录过期');
                // n9.context.$store.commit("CLEAR_NAVTAB_CACHE");
                // n9.context.util.deleteSession("user");
                store.commit("CLEAR_NAVTAB_CACHE");
                Util.deleteSession("user");
                ajax.loginTimeout();
                //数据异常
            } else if (res.data.code != 200) {
                if (failCallback && failCallback(res.data)) {
                    return false;
                }
                n9.error(res.data.msg || '服务器异常');
                // alert(JSON.stringify(res.data));
                console.log(res.data);

                //正常返回
            } else {
                // if (res.header && res.header['Set-Cookie']) {
                //     saveCookie(res.header['Set-Cookie']);
                // }
                if (successCallback) {
                    successCallback(res.data);
                }
            }
        }).catch(function (error) {
            // n9.error(JSON.stringify(error))
            if (failCallback && failCallback(error.data)) {
                return false;
            }
            console.log(error)
            n9.error('请求服务器失败，请检查网络')
            // alert("error\n" + JSON.stringify(error));
        });

        return request;
    },
    get(url, p1, p2, p3) {
        if (!p1) {
            return ajax.ajax('get', url, p2, p3);
        } else if (typeof p1 == 'function') {
            return ajax.ajax('get', url, null, p1, p2);
        } else {
            return ajax.ajax('get', url, p1, p2, p3);
        }
    },
    delete(url, callback, error) {
        return ajax.ajax('delete', url, null, callback, error);
    },
    deleteList(url, arr, callback) {
        var promises = [];
        arr.forEach((val, i)=>{
            promises.push(new Promise(function (succ, err) {
                ajax.delete((url.endWith("/") ? url : url + "/") + val.id, function () {
                    succ(val.id);
                }, function () {
                    succ(false)
                });
            }));
        })
        return Promise.all(promises).then((res)=>{
            var deletedIds = [];
            res.forEach(function (v) {
                console.log(v);
                if (v) {
                    console.log("del")
                    deletedIds.push(v);
                }
            })
            // console.log(res)
            if (callback && deletedIds.length > 0) {
                callback(deletedIds);
            }
        });
    },
    post(url, p1, p2, p3) {
        // var m = env === 'development' ? 'get' : "post";
        var m = 'post';
        if (!p1) {
            return ajax.ajax(m, url, p2, p3);
        } else if (typeof p1 == 'function') {
            return ajax.ajax(m, url, null, p1, p2);
        } else {
            return ajax.ajax(m, url, p1, p2, p3);
        }
    },
    upload(url, params, successCallback, errorCallback, config) {
        var c = {headers:{'Content-Type':'multipart/form-data'}, transformRequest: null};
        if (config) {
            for (var key in config) {
                c[key] = config[key];
            }
        }
        return ajax.ajax("post", url, params, successCallback, errorCallback, c);
    },
    put(url, params, successCallback, errorCallback) {
        return ajax.ajax('put', url, params, successCallback, errorCallback);
    }
}

const http = axios.create({
    baseURL: ajax.baseUrl,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-Requested-With': 'XMLHttpRequest'
    },
    withCredentials: true
});

export default ajax;